package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.ec.v2.utlis.Md5Util;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 易融信息 API
 */
@Service
public class YiRongApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();



        long timeStamp = System.currentTimeMillis();


        String appId = pushApiKeyParam.getApiKey();
        String appSecret = pushApiKeyParam.getApiSecret();
        String sign = getSign(timeStamp, appId, appSecret);


        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        headMap.put("X-Ec-Cid", pushApiKeyParam.getApiCode());
        headMap.put("X-Ec-Sign", sign);
        headMap.put("X-Ec-TimeStamp", String.valueOf(timeStamp));


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("typeId", 9);
        paramMap.put("type", 1);
        paramMap.put("value", memberSourceInfo.getMobileMd5());




        log.info("【易融信息】撞库开始【queryUrl】{}【paramMap】{}", queryUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createGet(queryUrl)
                .header("Content-Type", "application/json")
                .headerMap(headMap, true)
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【易融信息】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        log.info("撞库结果resultObject : {}", resultObject);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200") ) {
            JSONObject data = resultObject.getJSONObject("data");
            Boolean isRepeat = data.getBoolean("isRepeat");
            pushApiResult.setCode(code + "|"+isRepeat);
            if(!isRepeat){
                pushApiResult.setPushSuccess(true);
            }
        }

        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        return null;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) {
        String timeStampString = Long.toString(System.currentTimeMillis());

        String appId = pushApiKeyParam.getApiKey();
        String appSecret = pushApiKeyParam.getApiSecret();
        String sign = getSign(Long.valueOf(timeStampString), appId, appSecret);

        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        headMap.put("X-Ec-Cid", pushApiKeyParam.getApiCode());
        headMap.put("X-Ec-Sign", sign);
        headMap.put("X-Ec-TimeStamp", timeStampString);
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createDate = memberSourceInfo.getCreateTime().format(fmt);

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("optUserId",20969054);
        JSONArray objects = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("followUserId",Long.valueOf(pushApiKeyParam.getPriKey()));
        jsonObject.put("name",memberSourceInfo.getRealname());
        jsonObject.put("gender",memberSourceInfo.getSex());
        jsonObject.put("birthday",getBirthFromIdCard(memberSourceInfo.getAge()));
        jsonObject.put("mobile",memberSourceInfo.getMobile());
        jsonObject.put("memo",
                "客户要贷款：" + BaseTypeInfoEnum.LoanAmount.getNameByValue(memberSourceInfo.getLoanAmount()) + "  " + BaseTypeInfoEnum.LoanTime.getNameByValue(memberSourceInfo.getLoanTime()) + "||"
                        + "申请时间：" + createDate
                        + "车产情况：" + BaseTypeInfoEnum.Car.getNameByValue(memberSourceInfo.getCar()) + "||"
                        + "房车情况：" + BaseTypeInfoEnum.House.getNameByValue(memberSourceInfo.getHouse()) + "||"
                        + "公积金情况：" + BaseTypeInfoEnum.Gjj.getNameByValue(memberSourceInfo.getGjj()) + "||"
                        + "逾期情况：" + BaseTypeInfoEnum.Yuqi.getNameByValue(memberSourceInfo.getYuqi()) + "||"
        );
        jsonObject.put("channelId",pushApiKeyParam.getPubKey());
        StringBuilder prefecture = new StringBuilder();

        prefecture.append("中国").append("|").append(memberSourceInfo.getProvince()).append("|").append(memberSourceInfo.getCity());
        jsonObject.put("prefecture",prefecture.toString());
        objects.add(jsonObject);
        paramMap.put("list",objects);

        log.info("【易融信息】导单开始【queryUrl】{}【paramMap】{}", requestUrl, JSON.toJSONString(paramMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .headerMap(headMap, true)
                .execute().body();
        log.info("【易融信息】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode("|" + code);
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }


    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();
        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        ProtocolParamResult paramResult = new ProtocolParamResult();
        return paramResult;
    }

    public static void main(String[] args) {
        long timeStamp = System.currentTimeMillis();


        String appId = "1164960248427970560";
        String appSecret = "VycZgdzdrVnnQbNZLPT";
        String sign = getSign(timeStamp, appId, appSecret);

        String requestUrl="https://open.workec.com/v2/customer/getChannelSource";


        Map<String, String> headMap = new HashMap<>();
        headMap.put("Content-Type", "application/json");
        headMap.put("X-Ec-Cid", "20246760");
        headMap.put("X-Ec-Sign", sign);
        headMap.put("X-Ec-TimeStamp", String.valueOf(timeStamp));



        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("corpId", "20246760");
        paramMap.put("appId", appId);
        paramMap.put("secret", appSecret);


        String result = HttpUtil.createGet(requestUrl)
                .headerMap(headMap, true)
                .form(paramMap)
                .execute().body();
        System.out.println(result);
    }

    public static String getSign(long timeStamp, String appId, String appSecret){
        StringBuffer buffer = new StringBuffer();
        buffer.append("appId="+appId);
        buffer.append("&appSecret="+appSecret);
        buffer.append("&timeStamp="+timeStamp);
        return Md5Util.encryptMd5(buffer.toString()).toUpperCase();
    }


    /**
     * 获取出生日期
     *
     * @return 返回字符串类型
     */
    public String getBirthFromIdCard(Integer age) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();

        // 计算出生年份
        LocalDate birthDate = currentDate.minusYears(age);

        // 格式化为 yyyy-MM-dd
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String formattedBirthDate = birthDate.format(formatter);
        return formattedBirthDate;
    }
}

